<?php
namespace app\farm\controller;
use app\ApiRest;

use app\farm\model\Coupon;
use app\farm\model\CouponRecord;
use app\farm\model\Evaluate;
use app\farm\model\Farmer;
use app\farm\model\ShopOrder;
use app\farm\model\ShopOrderGoods;
use app\farm\model\ShopRefund;
use app\publics\model\TmplConfig;
use app\farm\model\Address;
use app\farm\model\Car;
use app\farm\model\Config;
use app\farm\model\Goods;
use app\farm\model\MsgConfig;
use app\farm\model\Order;
use app\farm\model\OrderAddress;
use app\farm\model\OrderGoods;
use app\farm\model\RefundOrder;
use app\shfarmop\model\User;
use app\shop\controller\IndexWxPay;
use app\shop\model\SeckillList;
use longbingcore\wxcore\PayModel;
use think\App;
use think\facade\Db;
use think\Request;


class IndexOrder extends ApiRest
{

    protected $model;

    protected $refund_model;

    protected $order_goods_model;

    protected $app;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new ShopOrder();

        $this->app = $app;

        $this->refund_model = new ShopRefund();

        $this->order_goods_model = new ShopOrderGoods();

        autoCancelOrder($this->_uniacid);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function orderList(){
        //超时自动取消订单
        $this->model->autoCancelOrder($this->_uniacid,$this->getUserId());

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['pay_type'])){

            $dis[] = ['a.pay_type','=',$input['pay_type']];

        }

        $data = $this->model->indexDataList($dis,$where);

        $eva_model    = new Evaluate();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $can_refund_num = is_array($v['order_goods'])?array_sum(array_column($v['order_goods'],'can_refund_num')):0;

                if(!empty($v['add_price'])&&$v['add_price_refund']==0){

                    $can_refund_num+=1;
                }
                //是否可以申请退款
                if(($v['pay_type']==7&&$v['can_refund_time']>time()&&$can_refund_num>0)||($v['pay_type']==2&&$can_refund_num>0)){

                    $v['can_refund'] = 1;

                }else{

                    $v['can_refund'] = 0;
                }

                $dis = [

                    'user_id' => $this->getUserId(),

                    'order_id'=> $v['id'],

                    'type'    => 3
                ];

                $have_eva = $eva_model->where($dis)->where('status','>',-1)->find();
                //是否已经评价
                $v['have_eva'] = !empty($have_eva)?1:0;

            }

        }

        $arr = [
            //未支付
            'no_pay_count'   => 1,
            //未发货
            'no_send_count'  => 2,
            //已经发货
            'have_send_count'=> 3
        ];

        foreach ($arr as $ks=>$vs){

            $map = [

                'user_id' => $this->getUserId(),

                'pay_type'=> $vs
            ];

            $data[$ks] = $this->model->where($map)->count();
        }

        return $this->success($data);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-15 14:58
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $input = $this->_param;


        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        $data['over_time'] -= time();

        $time_arr = ['create_time','pay_time','end_time','hx_time','cancel_time'];

        foreach ($time_arr as $v){

            $data[$v] = !empty($data[$v])?date('Y-m-d H:i:s',$data[$v]):$data[$v];

        }

        $data['distance'] = distance_text($data['distance']);

        $end_time = date('H:i',$data['send_end_time'])=='00:00'?'24:00':date('H:i',$data['send_end_time']);
        //配送时间
        $data['user_send_time'] = date('Y-m-d H:i',$data['send_start_time']).'~'.$end_time;
        //剩余可申请退款数量
        $can_refund_num = array_sum(array_column($data['order_goods'],'can_refund_num'));
        //是否可以申请退款
        if(($data['pay_type']==7&&$data['can_refund_time']>time()&&$can_refund_num>0)||($data['pay_type']==2&&$can_refund_num>0)){

            $data['can_refund'] = 1;

        }else{

            $data['can_refund'] = 0;
        }

        $farmer_model = new Farmer();

        $data['farmer_info'] = $farmer_model->dataInfo(['id'=>$data['farmer_id']],'title');

        $dis = [

            'user_id' => $this->getUserId(),

            'order_id'=> $data['id'],

            'type'    => 3
        ];

        $eva_model    = new Evaluate();

        $have_eva = $eva_model->where($dis)->where('status','>',-1)->find();
        //是否已经评价
        $data['have_eva'] = !empty($have_eva)?1:0;

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:29
     * @功能说明:退款订单详情
     *
     */
    public function refundOrderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];

        }

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];

        }

        $data = $this->refund_model->indexDataList($dis,$where);

        $map = [

            'status' => 1,

            'user_id'=> $this->getUserId()
        ];
        //退款中数量
        $data['ing_count'] = $this->refund_model->where($map)->count();

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 17:50
     * @功能说明:退款订单详情
     */

    public function refundOrderInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->refund_model->dataInfo($dis);

        $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);

        $data['refund_time'] = date('Y-m-d H:i:s',$data['refund_time']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-01 16:08
     * @功能说明:配送方式
     */
    public function goodsSendType(){

        $input = $this->_param;

        $car_model = new Car();

        $is_show = isset($input['is_show'])?$input['is_show']:1;

        $list = $car_model->carList($this->getUserId(),1,0,$is_show);

        $data['is_self'] = 0;

        $data['is_send'] = 0;

        if(!empty($list)){

            foreach ($list as &$value){

                $data['is_self'] = !empty($value['is_self'])?$value['is_self']:$data['is_self'];

                $data['is_send'] = !empty($value['is_send'])?$value['is_send']:$data['is_send'];

            }

        }

        return $this->success($data);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:43
     * @功能说明:下单页面详情
     */
    public function payOrderInfo(){

        $input = $this->_param;

        $coupon_id  = isset($input['coupon_id'])?$input['coupon_id']:0;

        $is_show    = isset($input['is_show'])?$input['is_show']:1;

        $send_type  = isset($input['send_type'])?$input['send_type']:2;

        $no_i       = isset($input['no_i'])?$input['no_i']:1;

        $address_model = new Address();

        $defult_address = $address_model->dataInfo(['user_id'=>$this->getUserId(),'status'=>1]);

        $defult_address_id = !empty($defult_address)?$defult_address['id']:0;

        $address_id = !empty($input['address_id'])?$input['address_id']:$defult_address_id;

        $order_info = $this->model->payOrderInfo($this->getUserId(),0,$coupon_id,$address_id,$is_show,$send_type,$no_i);

        if(!empty($input['address_id'])){
            //默认地址
            $order_info['address'] = $address_model->dataInfo(['id'=>$input['address_id']]);

        }else{

            $order_info['address'] = $defult_address;

        }

        $coupon_modle  = new Coupon();

        $coupon_record_model  = new CouponRecord();
        //可用优惠券数量
        $canUseCoupon = $coupon_modle->canUseCoupon($this->getUserId(),$order_info['goods_price']);

        $order_info['canUseCoupon'] = $coupon_record_model->where('id','in',$canUseCoupon)->sum('num');
        //模版消息model
        $tmpl_model = new TmplConfig();
        //获取模版
        $data['tmp_list'] = $tmpl_model->where(['uniacid'=>$this->_uniacid])->where('tmpl_name','in',['shop_order','send_over'])->select()->toArray();

        return $this->success($order_info);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 09:53
     * @功能说明:下单
     */
    public function payOrder(){

        $input = $this->_input;

        $send_type  = isset($input['send_type'])?$input['send_type']:2;

        $coupon_id  = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $address_id = isset($input['address_id'])?$input['address_id']:0;

        $is_show    = isset($input['is_show'])?$input['is_show']:1;

        $no_i       = isset($input['no_i'])?$input['no_i']:1;

        $order_info = $this->model->payOrderInfo($this->getUserId(),0,$coupon_id,$address_id,$is_show,$send_type,$no_i);

        $config_model = new Config();

        $address_order_model = new OrderAddress();

        $config = $config_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $top_order_code = orderCode();

        $kill_model = new SeckillList();
        //校验秒杀活动
        $res = $kill_model->userCheck($this->getUserId(),$order_info['kill_atv_id'],$is_show);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        Db::startTrans();
        //按农场主生成多个订单
        foreach ($order_info['order_goods'] as $value){

            $order_insert = [

                'uniacid'    => $this->_uniacid,

                'order_code' => orderCode(),

                'top_order_code' => $top_order_code,

                'user_id'    => $this->getUserId(),

                'pay_price'  => $value['pay_price'],

                'get_integral'=> $value['pay_price'],

                'true_price' => $value['pay_price'],

                'pay_type'   => 1,

                'goods_price'=> $value['goods_price'],

                'farmer_id'  => $value['farmer_id'],

                'store_id'   => $value['farmer_id'],

                'init_price'   => $value['init_price'],

                'init_goods_price' => $value['init_goods_price'],

                'text'         => $input['text'],

                'over_time'    => !empty($order_info['kill_atv_id'])?time()+$order_info['kill_over_time']*60:time()+$config['over_time']*60,

                'send_type'    => $send_type,

                'discount'     => $value['coupon_discount'],

                'freight'      => $value['freight'],

                'distance'     => $value['distance'],

                'balance'      => $input['pay_model']==2?$value['pay_price']:0,

                'total_price'  => $order_info['pay_price'],

                'send_start_time' => $input['start_time'],

                'send_end_time'   => $input['end_time'],

                'pay_model'    => $input['pay_model'],

                'kill_atv_id'  => $order_info['kill_atv_id'],

                'kill_discount_price'  => $value['kill_discount_price'],

                'integral'     => $no_i==0?$value['integral']:0,

                'integral_discount_price' => $no_i==0?$value['integral_discount_price']:0,

            ];
            //下单
            $res = $this->model->dataAdd($order_insert);

            if($res!=1){

                Db::rollback();

                $this->errorMsg('下单失败');
            }

            $order_id = $this->model->getLastInsID();
            //添加下单地址
            $res = $address_order_model->orderAddressAdd($input['address_id'],$order_id,$send_type,5,$input);

            if(!empty($res['code'])){

                Db::rollback();

                $this->errorMsg($res['msg']);

            }

            $order_insert['id'] = $order_id;

            if(empty($order_info['order_goods'])){

                $this->errorMsg('订单错误');
            }
            //添加到子订单
            $res = $this->order_goods_model->orderGoodsAdd($value['goods_list'],$order_id,$this->getUserId(),$value['farmer_id'],$input['address_id']);

            if(!empty($res['code'])){

                Db::rollback();

                $this->errorMsg($res['msg']);
            }
            //使用优惠券
            if(!empty($order_info['coupon_id'])){

                $this->model->dataUpdate(['id'=>$order_id],['coupon_id'=>$coupon_id]);

            }
            //积分活动
            $res = $this->model->marketingCheck($order_insert,$value['goods_list']);

            if(!empty($res['code'])){

                Db::rollback();

                $this->errorMsg($res['msg']);

            }

        }
        //使用优惠券
        if(!empty($order_info['coupon_id'])){

            $coupon_record_model = new CouponRecord();

            $coupon_record_model->couponUse($order_info['coupon_id']);

        }

        Db::commit();
        //如果是0元
        if($order_info['pay_price']<=0){

            $this->model->orderResult($top_order_code,$top_order_code);

            return $this->success(true);
        }
        //余额支付
        if($input['pay_model']==2){

            $user_model = new \app\farm\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_info['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($top_order_code,$top_order_code);

            return $this->success(true);

        }elseif ($input['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters = $pay_model->aliPay($top_order_code,$order_info['pay_price'],'商场商品');

            $arr['pay_list']= $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];


        }else{
            //微信支付
            $pay_controller = new IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"商城",['type' => 'SchoolShop' , 'out_trade_no' => $top_order_code],$order_info['pay_price']);

            $arr['pay_list']= $jsApiParameters;

        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 15:59
     * @功能说明:重新支付
     */
    public function rePayOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }
        //余额支付
        if($order_insert['pay_model']==2){

            $user_model = new \app\massage\model\User();

            $user_balance= $user_model->where(['id'=>$this->getUserId()])->value('balance');

            if($user_balance<$order_insert['pay_price']){

                $this->errorMsg('余额不足');
            }

            $this->model->orderResult($order_insert['order_code'],$order_insert['order_code']);

            return $this->success(true);

        }elseif ($order_insert['pay_model']==3){

            $pay_model = new PayModel($this->payConfig());

            $jsApiParameters = $pay_model->aliPay($order_insert['order_code'],$order_insert['pay_price'],'商场商品');

            $arr['pay_list']= $jsApiParameters;

            $arr['order_code']= $order_insert['order_code'];

        }else{

            //微信支付
            $pay_controller = new IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"商城",['type' => 'SchoolShop' , 'out_trade_no' => $order_insert['order_code']],$order_insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;

        }

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 16:38
     * @功能说明:取消订单
     */

    public function cancelOrder(){

        $input = $this->_input;

        $order_insert = $this->model->dataInfo(['id'=>$input['id']]);

        if($order_insert['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }

       $res = $this->model->cancelOrder($order_insert);

       if(!empty($res['code'])){

           $this->errorMsg($res['msg']);
       }

       return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 11:39
     * @功能说明:申请退款
     */
    public function applyOrder(){

        $input = $this->_input;

        $order = $this->model->dataInfo(['id'=>$input['order_id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if($order['pay_type']<2&&$order['have_tx']!=0){

            $this->errorMsg('订单状态错误');

        }

        if(empty($input['list'])){

            $this->errorMsg('请选择商品');

        }

        if($order['can_refund_time']<time()&&$order['pay_type']==7){

            $this->errorMsg('核销后24小时内才能申请退款哦');

        }
        //申请退款
        $res = $this->refund_model->applyRefund($order,$input);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-26 15:55
     * @功能说明:取消退款
     */
    public function cancelRefundOrder(){

        $input = $this->_input;

        $order = $this->refund_model->dataInfo(['id'=>$input['id']]);

        if($order['status']!=1){

            $this->errorMsg('订单已经审核');

        }

        Db::startTrans();

        $res = $this->refund_model->dataUpdate(['id'=>$input['id']],['status'=>-1,'cancel_time'=>time()]);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('取消失败');
        }

        if(!empty($order['order_goods'])){

            $order_goods_model = new ShopOrderGoods();

            foreach ($order['order_goods'] as $v){

                if(!empty($v['order_goods_id'])){

                    $num = $v['goods_num'];

                    $res = $order_goods_model->where(['id'=>$v['order_goods_id']])->update(['can_refund_num'=>Db::Raw("can_refund_num+$num")]);

                    if($res!=1){

                        Db::rollback();

                        $this->errorMsg('取消失败');
                    }

                }else{

                    $this->model->dataUpdate(['id'=>$order['order_id']],['add_price_refund'=>0]);

                }

            }

        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-04-07 15:30
     * @功能说明:刷新订单二维码
     */
    public function refreshQr(){

        $input = $this->_input;

        $qr_insert = [

            'id' => $input['id']
        ];
        //获取二维码
        $qr = $this->model->orderQr($qr_insert,$this->_uniacid);

        if(!empty($qr)){

            $this->model->dataUpdate(['id'=>$input['id']],['qr'=>$qr]);

        }

        return $this->success($qr);
    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-25 17:14
     * @功能说明:楼长核销订单
     */
    public function endOrder(){

        $input = $this->_input;

        $order_model= new ShopOrder();

        $order = $order_model->dataInfo(['id'=>$input['id']]);

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }

        if(empty($order)){

            $this->errorMsg('订单未找到');
        }
        //自提
        if($order['send_type']==1&&$order['pay_type']!=2){

            $this->errorMsg('订单状态错误');
        }
        //快递
        if($order['send_type']==2&&$order['pay_type']!=3){

            $this->errorMsg('订单状态错误');
        }

        $refund_model = new ShopRefund();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$order['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理再核销');

        }

        $res = $order_model->hxOrder($input['id'],$this->getUserId());

        return $this->success($res);


    }

    public function getPayNumber(){

        $input = $this->_input;

        $number= $this->order_goods_model->getGoodsNumber(['a.goods_id'=>$input['id'],'b.user_id'=>$this->getUserId()] );

        return $this->success(['number'=>$number]);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-10 00:40
     * @功能说明:可用的优惠券列表
     */
    public function couponList(){

        $input = $this->_param;

        $coupon_model = new Coupon();

        $coupon_record_model = new CouponRecord();

        $is_show   = isset($input['is_show'])?$input['is_show']:1;

        $send_type  = isset($input['send_type'])?$input['send_type']:2;

        $no_i       = isset($input['no_i'])?$input['no_i']:1;

        $order_info = $this->model->payOrderInfo($this->getUserId(),0,0,0,$is_show,$send_type,$no_i);

        $coupon_id = $coupon_model->canUseCoupon($this->getUserId(),$order_info['goods_price'],1);

        $data = $coupon_record_model->where('id','in',$coupon_id)->order('id desc')->paginate(10)->toArray();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-16 14:42
     * @功能说明:订阅消息通知
     */
    public function tmplList(){

        $tmpl_model = new TmplConfig();

        $dis = [

            'uniacid' => $this->_uniacid
        ];

        $data = $tmpl_model->where($dis)->select()->toArray();

        return $this->success($data);


    }






}
